package com.tc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: tianchao
 * @Date: 2021/12/9 21:23
 * @Description:
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    ThreadLocal<String> threadLocal = new ThreadLocal<>();
    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String s = System.currentTimeMillis() + "";
                threadLocal.set(s);
                logger.info("=================请求来了================{},{}",request.getServletPath(),s);
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                logger.info("=================请求结束================{},{}",request.getServletPath(),threadLocal.get());
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                logger.info("================================={}",request.getServletPath());
            }
        });
    }
}
